<?php
require_once SHMS_CORE_PATH."/shms_db_common.inc";
require_once SHMS_CORE_PATH."/shms_core_constants.inc";


function shms_core_db_get_person_array_struc(){
  return array(
      'id','duid','personal_detail_filled','full_name','matric_no',
      'phone_number', 'nus_email', 'personal_email','gender', 'date_of_birth', 
      'residential_status', 'nationality', 'major', 'home_faculty', 'year_of_intake',
      'year_of_graduation');
}

/**
 * load all data for a person -- including the person basic info, and all person by year info
 * @return
 *  - empty array when the person_id doesn't exist
 *  - an array keyed with: 'basic', and 'by_year'
 */
function shms_core_db_load_all_data_for_person($person_id){
  $query = db_select(SHMS_PERSON_TABLE,'p');
  $query->condition('p.id',$person_id);
  $query->fields('p');
  $person_basic_info = $query->execute()->fetchAssoc();
  if(empty($person_basic_info)) return array();
  
  // load the person_by_year info
  $query = db_select(SHMS_PERSON_BY_YEAR_TABLE,'py');
  return array(
    'basic' => $person_basic_info,
    'by_year' => $query->orderBy('py.year','DESC')->condition('py.pid',$person_id)->fields('py')->execute()->fetchAllAssoc('id',PDO::FETCH_ASSOC),
  );
}

/**
 * Add person into the database, the $person is an array which must contain:
 *  - full_name
 *  - matric_no
 *  - room_number
 *  
 *  - personal_detail_filled -- boolean, when this is true, the following is also
 *                              required; otherwise, below are optional:
 *    - gender
 *    - date_of_birth
 *    - phone_number
 *    - nus_email
 *    - personal_email
 *    - residental_status
 *    - nationality
 *    - major
 *    - home_faculty
 *    - year_of_intake
 *    - year_of_graduation
 */
function shms_core_db_add_person($person){
  // Check if the data comes as required
  static $basic_mandatory_info = array('full_name','matric_no','personal_detail_filled');
  static $additional_info = array( 
      'gender', 'date_of_birth', 'phone_number', 'nus_email', 'personal_email', 
      'residential_status', 'nationality', 'home_faculty', 
      'year_of_intake', 'year_of_graduation');
  shms_core_db_make_sure_field_exists($person, $basic_mandatory_info,"Mandatory field in shms_core_db_add_person function");
  if($person['personal_detail_filled']) 
    shms_core_db_make_sure_field_exists($person, $additional_info,"Additional field in shms_core_db_add_person function");
  
  $transaction = db_transaction();
  try{
    
    // grant this user a drupal account, password set to be the same as the matric number
    $pmatric = $person['matric_no'];
    $new_account = new stdClass();
    $new_account->name = $pmatric;
    $new_account->mail = empty($person['personal_email']) ? 
                  $pmatric."@nus.edu.sg":
                  $person['personal_email'];
    $new_account->status = 1;
    
    require_once DRUPAL_ROOT . "/" . variable_get("password_inc","includes/password.inc");
    $new_account->pass = user_hash_password($pmatric);
    $new_account->roles = array(SHMSR_RESIDENT);
    
    $roles = user_roles();
    $rid = array_search(SHMSR_RESIDENT,$roles);
    
    if(!($new_account = user_save($new_account,array('roles'=>array($rid=>SHMSR_RESIDENT))))){
      throw new Exception("Cannot add drupal account");
    }
    
    // then add to person table
    $person['duid'] = $new_account->uid;
    if(drupal_write_record(SHMS_PERSON_TABLE, $person) != SAVED_NEW){
      throw new Exception("Duplicated Person Table Record");
    }
    
    // then an instance into the person year table
    $person_by_year = array(
      'pid' => $person['id'],
      'room_number' => $person['room_number'],
      'year'  => shms_get_current_academic_year(),
      'sem'  => 0,  // assume to be full year resident
    );
    if(drupal_write_record(SHMS_PERSON_BY_YEAR_TABLE, $person_by_year)!= SAVED_NEW){
      throw new Exception("Duplicated Person Record");
    }
  } catch(Exception $e){
    $transaction->rollback();
    watchdog("ADD PERSON ERROR",$e);
    return FALSE;
  }
  
  return TRUE;
}

function shms_core_db_update_person($person_info){
 $res = db_update(SHMS_PERSON_TABLE)->fields($person_info)->condition('id',$person_info['id'])->execute();
 return TRUE;
}
